package com.bra.ui.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bra.R;
import com.bra.bean.VenueDetailsBean;
import com.bra.bean.VenueBean;
import com.bra.bean.CommentBean;
import com.bra.request.UrlConstants;
import com.bra.ui.adapter.Comment_adapter;
import com.bra.ui.adapter.VenueDetails_Recommend_adapter;
import com.bra.ui.adapter.VenueDetails_advance_adapter;
import com.bra.ui.adapter.VenueList_adapter;
import com.bra.ui.adapter.VenueDetails_ballgame_Adapter;
import com.bra.ui.adapter.SelectVenue_advance_adapter;
import com.bra.ui.base.BaseActivity;
import com.bra.utils.DialogUtil;
import com.bra.utils.SPHelper;
import com.bra.utils.StringHelper;
import com.bra.utils.ToastUtil;
import com.bra.utils.DialogAct;
import com.bra.utils.DialogAct.MyDialogListener;
import com.bra.view.Hsv_Recommend;
import com.bra.view.Hsv_advance;
import com.bra.view.ImagerLoaderHelper;
import com.bra.view.MyHorizontalScrollView;
import com.bra.view.MyHorizontalScrollView.CurrentImageChangeListener;
import com.bra.view.MyHorizontalScrollView.OnItemClickListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.ShareContent;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

/**
 * 场馆详情界面
 * 
 * @author lenovo
 *
 */
public class VenueDetailsActivity extends BaseActivity {
	private TextView activity_title, cdxq_map_text, cdxq_phone_tv, cgxq_name,
			cgxq_beizhu, cgxq_mianfei;
	private ImageView activity_back, activity_shoucang, cgxq_image;
	private LinearLayout cgxq_title;
	private RelativeLayout cdxq_map, cdxq_phone;
	private VenueDetails_Recommend_adapter TJ_adapter;
	private String[] items = new String[7];	

	private MyHorizontalScrollView mHorizontalScrollView;
	private VenueDetails_ballgame_Adapter mAdapter;
	private String info;
	private ListView cgxq_pinglun_list;
	private Comment_adapter adapter;
	private VenueDetails_advance_adapter yudign_adapter;
	private Hsv_Recommend movieLayout;
	private Hsv_advance movieLayout_yuding;
	private List<CommentBean> comments;
	private Bundle bundle;
	private String id, fraction, projectId;
	private RequestQueue mRequestQueue;
	private String Play_XqUrl = UrlConstants.IP;
	private CommentBean commnemt;
	private List<CommentBean> commnemts;
	private RatingBar cgxq_rb;
	private ImageLoader imageLoader;
	private ImagerLoaderHelper imageLoaderHelper;
	private String userid, token;
	private boolean Is_Login;
	private String isCollection="";
	private List<VenueDetailsBean>cgxqbeans;
	private  VenueDetailsBean cgxqbean;

	@Override
	protected View onCreateView(LayoutInflater inflater,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.activity_venuedetails, null);
	}

	@Override
	protected void onViewCreated(Bundle savedInstanceState) {
		mRequestQueue = Volley.newRequestQueue(this);
		imageLoader = ImageLoader.getInstance();
		imageLoaderHelper = ImagerLoaderHelper.getInstance();
		userid = SPHelper.readString(VenueDetailsActivity.this, "userId");
		token = SPHelper.readString(VenueDetailsActivity.this, "token");
		Is_Login = SPHelper.readBoolean(this, "Is_Login", false);
		bundle = getIntent().getExtras();
		id = bundle.getString("id");
		fraction = bundle.getString("fraction");
		projectId = bundle.getString("projectId");
		activity_title = (TextView) findViewById(R.id.activity_title);
		activity_title.setText("场馆详情");
		activity_back = (ImageView) findViewById(R.id.activity_back);
		cgxq_title = (LinearLayout) findViewById(R.id.cgxq_title);
		cgxq_title.setVisibility(View.VISIBLE);
		activity_shoucang = (ImageView) findViewById(R.id.activity_shoucang);
		cdxq_map = (RelativeLayout) findViewById(R.id.cdxq_map);
		cdxq_phone = (RelativeLayout) findViewById(R.id.cdxq_phone);
		cdxq_map_text = (TextView) findViewById(R.id.cdxq_map_text);
		cdxq_phone_tv = (TextView) findViewById(R.id.cdxq_phone_tv);
		mHorizontalScrollView = (MyHorizontalScrollView) findViewById(R.id.id_horizontalScrollView);

		cgxq_image = (ImageView) findViewById(R.id.cgxq_image);
		cgxq_name = (TextView) findViewById(R.id.cgxq_name);
		cgxq_rb = (RatingBar) findViewById(R.id.cgxq_rb);
		cgxq_mianfei = (TextView) findViewById(R.id.cgxq_mianfei);
		cgxq_beizhu = (TextView) findViewById(R.id.cgxq_beizhu);
		// 预定
		movieLayout_yuding = (Hsv_advance) findViewById(R.id.movieLayout_yuding);		
		// 推荐
	    movieLayout = (Hsv_Recommend) findViewById(R.id.movieLayout);
		for (int i = 0; i < items.length; i++) {

			items[i] = "龙德羽毛球馆" + i;
		}
		// 添加滚动回调
		mHorizontalScrollView
				.setCurrentImageChangeListener(new CurrentImageChangeListener() {
					@Override
					public void onCurrentImgChanged(int position,
							View viewIndicator) {
						TextView qiulei_text = (TextView) viewIndicator
								.findViewById(R.id.cdxq_qiulei_text);
						qiulei_text.setTextColor(getResources().getColor(
								R.color.color_e6e6e6));

					}
				});
		// 添加点击回调
		mHorizontalScrollView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onClick(View view, int position) {

				TextView qiulei_text = (TextView) view
						.findViewById(R.id.cdxq_qiulei_text);
				qiulei_text.setTextColor(getResources().getColor(
						R.color.color_e6e6e6));
			/*	if (yudign_adapter == null) {
					yudign_adapter = new VenueDetails_advance_adapter(Cgxq_Activity.this,arr);
				}
				movieLayout_yuding.setAdapter(yudign_adapter);	*/	
				httpRequestFenLeiImageInfo(VenueDetailsActivity.this,Play_XqUrl,userid,token,id,cgxqbeans.get(position).getId());
			}
		});
		
		
		if (TJ_adapter == null) {
			TJ_adapter = new VenueDetails_Recommend_adapter(VenueDetailsActivity.this, items);
		}
		movieLayout.setAdapter(TJ_adapter);

		// 评论listview
		cgxq_pinglun_list = (ListView) findViewById(R.id.cgxq_pinglun_list);
		httpRequestPlayXqInfo(VenueDetailsActivity.this, Play_XqUrl,RequestParams(userid,token,id, projectId));
	}

	public List<CommentBean> getdata() {
		comments = new ArrayList<CommentBean>();
		for (int i = 0; i < 4; i++) {
			CommentBean comment = new CommentBean();
			String info = "中华小子" + i;
			comment.setContent(info);
			comments.add(comment);
		}
		return comments;
	}

	@Override
	protected void setListener() {
		activity_back.setOnClickListener(click);
		activity_shoucang.setOnClickListener(click);
		cdxq_map.setOnClickListener(click);
		cdxq_phone.setOnClickListener(click);
		cgxq_image.setOnClickListener(click);
	}

	private Dialog dialog;
	private boolean Is_shoucang;
	private View.OnClickListener click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.activity_back:
				finish();
				break;
			case R.id.activity_shoucang:
				// shareboard(Cgxq_Activity.this); //分享
				if (!Is_Login) {
					goActivity(LoginActivity.class);
				} else {	
					String shoucang = "Add_Collection_Api";
					String notshoucang = "Cancel_Collection_Api";
					//收藏
					if (isCollection!=null) {
						if ("0".equals(isCollection)) {													
							httpRequestshoucangInfo(VenueDetailsActivity.this, Play_XqUrl,shoucang, userid, token, id);
						}else if("1".equals(isCollection)){
							//取消收藏			
							httpRequestNotScInfo(VenueDetailsActivity.this, Play_XqUrl,notshoucang, userid, token, id);
						}
					}else{
						//去收藏								
						httpRequestshoucangInfo(VenueDetailsActivity.this, Play_XqUrl,shoucang, userid, token, id);
					}
				}

				break;
			case R.id.cdxq_map:
				Bundle bundle = new Bundle();
				bundle.putString("address", cdxq_map_text.getText().toString());
				goActivity(MapActivity.class, bundle);
				break;
			case R.id.cdxq_phone:
				final String forPhoneNum = cdxq_phone_tv.getText().toString();
				String submit = "拨打",
				cancle = "取消";
				if (dialog == null) {
					dialog = new DialogAct(VenueDetailsActivity.this,
							R.layout.dialog_exit, forPhoneNum, submit, cancle,
							new MyDialogListener() {

								@Override
								public void onClickListener(View view) {
									Intent intent = new Intent();
									intent.setAction("android.intent.action.CALL");
									intent.setData(Uri.parse("tel:"
											+ forPhoneNum));
									startActivity(intent);
								}
							});
				}
				dialog.show();
				break;
				
			case R.id.cgxq_image:
				Bundle address = new Bundle();
				address.putString("address", cdxq_map_text.getText().toString());
				goActivity(MapActivity.class, address);
				break;
			default:
				break;
			}

		}
	};

	// 分享
	public void shareboard(Activity activity) {
		final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[] {
				SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ,
				SHARE_MEDIA.QZONE, SHARE_MEDIA.SINA };
		new ShareAction(activity)
				.setDisplayList(displaylist)
				// .setContentList(new ShareContent(),new ShareContent())
				// //不同的平台不同的内容
				.withText("你的健康，我的骄傲")
				.withTitle("欢迎使用博云瑞动")
				.withTargetUrl("http://www.baidu.com")
				.withMedia(
						new UMImage(activity, BitmapFactory.decodeResource(
								getResources(), R.drawable.cg_list_item_im)))
				.setListenerList(umShareListener, umShareListener)
				// .setShareboardclickCallback(shareBoardlistener)
				.open();
	}

	ShareBoardlistener shareBoardlistener = new ShareBoardlistener() {

		@Override
		public void onclick(SnsPlatform arg0, SHARE_MEDIA arg1) {
			// TODO Auto-generated method stub

		}
	};
	UMShareListener umShareListener = new UMShareListener() {

		@Override
		public void onResult(SHARE_MEDIA platform) {
			Toast.makeText(VenueDetailsActivity.this, platform + " 分享成功啦",
					Toast.LENGTH_SHORT).show();
		}

		public void onError(SHARE_MEDIA platform, Throwable arg1) {
			Toast.makeText(VenueDetailsActivity.this, platform + " 分享失败啦",
					Toast.LENGTH_SHORT).show();

		}

		@Override
		public void onCancel(SHARE_MEDIA platform) {
			Toast.makeText(VenueDetailsActivity.this, platform + " 分享取消了",
					Toast.LENGTH_SHORT).show();
		}
	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
	};
	 String[] arr;
    //场馆详情的网络请求
	private void httpRequestPlayXqInfo(Context context, String url,
			final HashMap<String, String> params) {
		StringRequest req = new StringRequest(Request.Method.POST, url,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						System.out.println(response.toString() + "==");
						commnemts = new ArrayList<CommentBean>();
						cgxqbeans= new ArrayList<VenueDetailsBean>();
						 List<Map> list = new ArrayList<Map>();
						try {
							JSONObject comment = new JSONObject(response
									.toString());
							// 场馆球类类别
							JSONArray fieldsArray = comment.getJSONArray("projects");
							for (int i = 0; i < fieldsArray.length(); i++) {
								JSONObject fieldsobject = fieldsArray.getJSONObject(i);
								String projectName = fieldsobject.getString("projectName");
								String projectid =fieldsobject.getString("id");
								JSONObject days_object=fieldsobject.getJSONObject("days");
								Map<String ,Object>maps=new HashMap<String, Object>();
								cgxqbean = new VenueDetailsBean(projectid,projectName);	
								for(int j=0;j<days_object.length();j++){
									String key=days_object.names().getString(j);
									String value=days_object.getString(key);
									cgxqbean.setKey(key);
									cgxqbean.setValue(value);
										 
								//	maps.put("key", key);
								//	maps.put("value", value);
								}
								cgxqbeans.add(cgxqbean);
							//	maps.put("projectid", projectid);
							//	maps.put("projectName", projectName);
							//	list.add(maps);
								//split(",");//分割字符串得到数组						    													    	       		
							}
												
							if(mAdapter==null){
								mAdapter = new VenueDetails_ballgame_Adapter(VenueDetailsActivity.this, cgxqbeans);
							}					
							mHorizontalScrollView.initDatas(mAdapter);
							if (yudign_adapter == null) {
								yudign_adapter = new VenueDetails_advance_adapter(VenueDetailsActivity.this,cgxqbeans);
							}
							movieLayout_yuding.setAdapter(yudign_adapter/*,id,cgxqbeans*/);
							
							
							// 其他信息
						/*	String cgxqimgSrc = comment.getString("imgSrc");// tupian
							String tel = comment.getString("tel");
							String name = comment.getString("name");
							String address = comment.getString("address");
							String remarks = comment.getString("remarks");// 备注
                           
							JSONObject vs = comment.getJSONObject("venueMoreService");// 免费
							String parking = vs.getString("parking");// 免费停车*/
							isCollection= comment.getString("isCollection");//是否收藏
							
							if("1".equals(isCollection)){
								activity_shoucang.setImageDrawable(getResources().getDrawable(R.drawable.shoucang_red));				
							}else{
								activity_shoucang.setImageDrawable(getResources().getDrawable(R.drawable.cg_title_shoucang));
							}
							// 文本配置信息
						/*	imageLoader.displayImage(cgxqimgSrc, cgxq_image,
									imageLoaderHelper.getOptions());
							cgxq_name.setText(name);
							cgxq_beizhu.setText(remarks);
							cgxq_mianfei.setText(parking);
							cgxq_rb.setRating(Float.parseFloat(fraction));
							cdxq_phone_tv.setText(tel);
							cdxq_map_text.setText(address);
							// 获取评论列表
							JSONArray array = comment
									.getJSONArray("commentList");
							for (int i = 0; i < array.length(); i++) {
								JSONObject object = array.getJSONObject(i);
								String content = object.getString("content");
								String username = object.getString("username");
								String createDate = object
										.getString("createDate");
								String imgSrc = object.getString("imgSrc");
								commnemt = new Comment_infoBean(content,
										username, createDate, imgSrc);
								commnemts.add(commnemt);
							}
							if (adapter == null) {
								adapter = new Comment_adapter(
										Cgxq_Activity.this, commnemts);
							}
							cgxq_pinglun_list.setAdapter(adapter);*/
							return;
						} catch (JSONException e) {

							e.printStackTrace();
						}
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError volleyError) {

					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> map = params;
				return map;
			}
		};
		mRequestQueue.add(req);
	}

	private HashMap<String, String> RequestParams(String userId,String token, String id, String projectId) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("userId", userId);
		map.put("equipment", "android");
		map.put("requestType", "View_Venue_Api");
		map.put("token", token);
		map.put("id", id);
		map.put("projectId", projectId);
		return map;
	}

	// 收藏网络请求
	private void httpRequestshoucangInfo(Context context, String url,
			String api, String userid, String token, String id) {

		AsyncHttpClient client = new AsyncHttpClient();
		// 创建请求参数
		RequestParams params = new RequestParams();
		params.put("userId", userid);
		params.put("equipment", "android");
		params.put("requestType", api);
		params.put("token", token);
		params.put("modelId", id);
		params.put("modelKey", "venue");
		// 执行post方法
		client.post(url, params, new JsonHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				Toast.makeText(VenueDetailsActivity.this, "网络错误", 0).show();
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);
				try {
					String code = response.getString("status_code");
					if (code.equals(200 + "")) {
						ToastUtil.showToast(VenueDetailsActivity.this, "场馆收藏成功");
						isCollection = "1";
						activity_shoucang.setImageDrawable(getResources().getDrawable(R.drawable.shoucang_red));						
					} else {
						ToastUtil.showToast(VenueDetailsActivity.this, "场馆收藏失败");
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});
	}

	// 取消收藏的网络请求
	private void httpRequestNotScInfo(Context context, String url, String api,
			String userid, String token, String id) {

		AsyncHttpClient client = new AsyncHttpClient();
		// 创建请求参数
		RequestParams params = new RequestParams();
		params.put("userId", userid);
		params.put("equipment", "android");
		params.put("requestType", api);
		params.put("token", token);
		params.put("modelId", id);
		params.put("modelKey", "venue");
		// 执行post方法
		client.post(url, params, new JsonHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				Toast.makeText(VenueDetailsActivity.this, "网络错误", 0).show();
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				// TODO Auto-generated method stub
				super.onSuccess(statusCode, headers, response);
				try {
					String code = response.getString("status_code");
					if (code.equals(200 + "")) {
						isCollection = "0";
						ToastUtil.showToast(VenueDetailsActivity.this, "场馆取消收藏成功");
						activity_shoucang.setImageDrawable(getResources().getDrawable(R.drawable.cg_title_shoucang));
					} else {
						ToastUtil.showToast(VenueDetailsActivity.this, "场馆取消收藏失败");
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		 });
	}
	   //运动项目分类的网络请求
		private void httpRequestFenLeiImageInfo(Context context, String url,
				String userid, String token, String id,String projectId) {

			AsyncHttpClient client = new AsyncHttpClient();
			// 创建请求参数
			RequestParams params = new RequestParams();
			params.put("userId", userid);
			params.put("equipment", "android");
			params.put("requestType", "Switch_Field_Api");
			params.put("token", token);
			params.put("id", id);
			params.put("projectId",projectId);
			// 执行post方法
			client.post(url, params, new JsonHttpResponseHandler() {

				@Override
				public void onFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					// TODO Auto-generated method stub
					super.onFailure(statusCode, headers, throwable, errorResponse);
					Toast.makeText(VenueDetailsActivity.this, "网络错误", 0).show();
				}

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						JSONObject response) {
					// TODO Auto-generated method stub
					super.onSuccess(statusCode, headers, response);
					System.out.println(response.toString());
					Toast.makeText(VenueDetailsActivity.this, response.toString(), 0).show();
					try {
						String code = response.getString("status_code");
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		}
}
